package com.shadowtorcher.stdisk.logic;

import com.shadowtorcher.soulknife.SoulKnifeDB;
import com.shadowtorcher.soulknife.exception.BeanConfigErrorException;
import com.shadowtorcher.stdisk.bean.*;
import com.shadowtorcher.stdisk.util.FileUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class DownloadUrlGenerator {
    private UserBean user;

    public DownloadUrlGenerator(UserBean user) {
        this.user = user;
    }

    public List<String> getUrl(String uuid) throws SQLException {
        try {
            LogicFileBean logicFile = SoulKnifeDB.selectWhere("LogicFileID = ?", uuid).setClass(LogicFileBean.class).get(0);
            return getUrl(logicFile);
        } catch (BeanConfigErrorException e) {
            e.printStackTrace();
        }
        throw new SQLException();
    }

    public List<String> getUrl(LogicFileBean logicFile) throws SQLException {
        List<String> list = new LinkedList<>();
        try {
            if (user == null) {
                if (logicFile.getPublic() != 0 ||
                        !SoulKnifeDB.selectWhere("LogicFileID = ?", logicFile.getLogicFileID()).
                                setClass(SharedFileBean.class).isEmpty()) {
                    this.user = new UserBean();
                    this.user.setUserName("anonymous");
                }
            }
            List<CdnBean> cdns = SoulKnifeDB.selectAll().setClass(CdnBean.class);
            String url = FileUtil.generateDownloadUrl(logicFile, user);
            for (CdnBean cdn : cdns) {
                if (!SoulKnifeDB.selectWhere("CdnId = ? and PhysicsFileID = ?",
                        cdn.getCdnId(), logicFile.getPhysicsFileID()).setClass(CdnFileBean.class).isEmpty())
                    list.add(cdn.getCdnUrl() + url);
            }
        } catch (BeanConfigErrorException e) {
            e.printStackTrace();
        }
        return new ArrayList<>(list);
    }
}
